<template>
  <div v-if="COMPLEXSTATE" class="approval-page">
    <div class="content">
      <div class="selection-container">
        <el-cascader
            v-if="!isStudent"
            v-model="selectedOptions"
            :options="cascaderOptions"
            :show-all-levels="false"
            placement="right-start"
            :props="{ expandTrigger: 'hover' }"
            placeholder="请选择专业和班级"
            @change="handleCascaderChange"
            filterable
            class="flex-item"
        ></el-cascader>

        <el-select @change="handleCascaderChange" v-model="selectedStatus" placeholder="请选择审批状态"
                   class="flex-item">
          <el-option label="已审批" value="1"></el-option>
          <el-option label="待审批" value="0"></el-option>
          <el-option label="未通过" value="3"></el-option>
        </el-select>
      </div>
      <h1 v-if="this.selectedOptions.at(2)&&!selectedStudent" style="text-align: center">
        该班级无{{ this.getState() }}数据
      </h1>
      <h1 v-else-if="!selectedStudent" style="text-align: center">
        请选择所需要审核的班级
      </h1>
      <!-- 根据当前选中项显示信息 -->
      <div v-if="selectedStudent" class="selected-info">
        <div class="info-line">
          <span>姓名: {{ selectedStudent.name }}</span>
          <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
          <span>学号: {{ selectedStudent.accountNo }}</span>
          <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
          <span>班级: {{ selectedStudent.classNo }}</span>
          <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
          <span>审批状态: {{ this.getState() }}</span>
          <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
          <span v-if="this.selectedStatus==='3'">未通过原因: {{ selectedStudent.rejection }}</span>
        </div>
        <div class="right-div">
          <StuList @click="nameClick(this.$store.state.studentIndex)" :students="this.students"></StuList>
        </div>
        <div>
          <img @click="previewImage(this.selectedItem().photoUrl)" v-if="this.selectedItem().photoUrl!==''"
               :src=" this.selectedItem().photoUrl" alt="证明材料"
               class="project-image">
          <h1 v-else>无证明材料</h1>
        </div>
      </div>
    </div>

    <!-- 分类、项目和分数 -->
    <div class="info-footer">
      <div v-if="selectedStudent" class="info-line" style="font-size: 1.6rem">
        <span>分类: {{ this.selectedItem().title }}</span>
        <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <span>项目: {{ this.selectedItem().name }}</span>
        <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <span>分数: {{ this.selectedItem().score }}</span>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons" v-if="selectedStudent">
      <el-button type="primary" @click="prevItem">上一项</el-button>
      <el-button type="danger" @click="reject">驳回</el-button>
      <el-button v-if="this.finish&&this.selectedStatus!=='1'" type="success" @click="getNextStudent">通过</el-button>
      <el-button type="primary" @click="this.addProjectDialog=true">添加项目</el-button>
      <div style="display: flex"><!--v-if="!complexCommittee(this.roleNo)" -->
        <h5>修改分数：</h5>
        <el-input-number :min="0" :value-on-clear="0" v-if="selectedStudent" v-model="this.selectedItem().score"></el-input-number>
      </div>
      <el-button v-if="this.finish" type="primary" @click="approve">整体查看</el-button>
      <el-button v-if="this.selectedStatus==='1'" type="success" @click="resetState">重新审批</el-button>
      <el-button v-if="this.finish&&this.selectedStatus==='1'" type="success" @click="getNextStudent">下一位同学
      </el-button>
      <el-button v-if="!this.finish" type="primary" @click="nextItem">下一项</el-button>
    </div>
  </div>
  <div style="text-align: center;font-size: 50px" v-else>
    综测未开放
  </div>
  <el-dialog
      v-model="this.$store.state.complexUpdate"
      :close-on-click-modal="false"
      title="综测详情信息"
      width="850px">
    <Complex v-if="this.$store.state.complexUpdate"/>
  </el-dialog>
  <el-dialog
      v-model="this.addProjectDialog"
      :close-on-click-modal="false"
      title="添加项目"
      width="500px">
    <div class="form-row">
      <div class="form-item">
        <label>项目类型</label>
        <el-select @change="this.selectComplexType" v-model="this.selectedComplexType" placeholder="请选择项目类型">
          <el-option v-for="item in complexType" :key="item.name" :label="item.name" :value="item"></el-option>
        </el-select>
      </div>
    </div>
    <div class="form-row">
      <div class="form-item">
        <label>加分项目</label>
        <el-input v-model="this.projectObject.name"></el-input>
      </div>
    </div>
    <div class="form-row">
      <div class="form-item">
        <label>分数(禁止为空或为负)</label>
        <el-input-number v-model="this.projectObject.score"></el-input-number>
      </div>
    </div>
    <div class="form-row">
      <label>证明材料</label>
      <el-upload
          accept=".jpeg,.png,.jpg"
          :before-upload="checkFileType"
          class="avatar-uploader"
          style="  border: 1px dashed #d9d9d9;
                    border-radius: 6px;
                    cursor: pointer;
                    position: relative;
                    overflow: hidden;"
          :action="'/api/complex_related/uploadPhoto'"
          :headers="this.headerObject"
          :show-file-list="false"
          :data="this.projectObject.photoUrl"
          :on-success="handleSuccess">
        <div style="width: 80px;height: 90px">
          <img width="80" :src="this.projectObject.photoUrl" :alt="this.projectObject.photoUrl">
        </div>
      </el-upload>
    </div>
    <el-button type="primary" @click="this.addProject()">确定</el-button>
  </el-dialog>
  <el-image-viewer v-if="imgViewerVisible" :onClose="closeViewer" :url-list="this.urlList"/>
</template>

<script>
import request from "@/util/request.js";
import {year,COMPLEXSTATE} from "../../../public/static/config.js";
import Complex from "@/template/Complex.vue";
import {complexCommittee} from "@/util/permissionJudgment.js";
import aes from "@/util/aes.js";
import StuList from "@/views/complex/StuList.vue";
import router from "@/router/index.js";
import {COMPLEX_MANAGER} from "@/util/config.js";

export default {
  components: {StuList, Complex},
  data() {
    return {
      isStudent:false,
      imgViewerVisible: false,
      urlList: [], // 预览照片
      finish: false,
      addProjectDialog: false,
      year: year,
      COMPLEXSTATE:COMPLEXSTATE,
      cascaderOptions: [],
      selectedOptions: [],
      students: [],
      items: [],
      selectedStudentIndex: 0,
      selectedItemIndex: 0,
      selectedStatus: "0",
      roleNo: [],
      complexType: [],// 综测类型
      selectedComplexType: {},
      projectObject: {title: '', complexTypeNo: "", name: '', score: 0, photoUrl: ''},
      headerObject: {
        "account": JSON.parse(localStorage.getItem('user')).accountNo,
        "token": JSON.parse(localStorage.getItem('user')).token
      },
    };
  },
  computed: {
    selectedStudent() {
      return this.students[this.selectedStudentIndex];
    }
  },
  created() {
    if (COMPLEXSTATE) {
      // 在综测成绩查看页面点击综测审批修携带accountNo和year
      if (router.currentRoute.value.query.accountNo !== undefined && router.currentRoute.value.query.year !== undefined) {
        let accountNo = router.currentRoute.value.query.accountNo
        this.year = router.currentRoute.value.query.year
        request.get("/complex_related/getOne?accountNo=" + accountNo + "&year=" + this.year).then(res => {
          // 给students赋值，用于显示右侧学生列表
          this.students.push(res.data.data)
          // 给items赋值用于显示当前学生综测信息
          this.items = this.students.at(this.selectedStudentIndex).contentList
          // 给selectedStatus赋值，用于审批状态
          this.selectedStatus = this.students.at(this.selectedStudentIndex).state
        })
      }
      // 获取班级信息
      // 如果是授予的学生权限
      let role = JSON.parse(localStorage.getItem("user")).roleNo;
      if (role.includes(COMPLEX_MANAGER)) {
        this.isStudent = true
        this.selectedOptions.push("")
        this.selectedOptions.push("")
        this.selectedOptions.push(JSON.parse(localStorage.getItem("user")).classNo)
        this.handleCascaderChange()
      } else {
        this.getClass()
      }
      // 用户角色编号
      this.setRoleNo()
      // 获取综测类型
      request.get("/complex_type/all").then(res => {
        this.complexType = res.data.data
      })
    }
  },
  methods: {
    // 关闭预览
    closeViewer() {
      if (this.imgViewerVisible) {
        this.imgViewerVisible = false
        this.urlList.pop();
      }
    },
    // 图片预览
    previewImage(src) {
      // 这里可以根据你的需求实现图片预览功能，比如弹出模态框等
      this.urlList.push(src)
      this.imgViewerVisible = true
    },
    // 点击添加项目按钮
    addProject() {
      this.$confirm('添加成功, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

      }).catch(() => {
        this.addProjectDialog = false
      })
      this.items.push(this.projectObject)
      this.selectedComplexType = {}
      this.projectObject = {title: '', complexTypeNo: "", name: '', score: 0, photoUrl: ''}
    },
    // 选择综测类型待审批、已审批、未通过
    selectComplexType(item) {
      this.projectObject.title = item.name
      this.projectObject.complexTypeNo = item.value
      console.log(this.projectObject)
    },
    // 点击右侧的名字
    nameClick(index) {
      console.log(index)
      this.finish = false
      this.selectedStudentIndex = index
      this.selectedItemIndex = 0
      this.items = this.students.at(this.selectedStudentIndex).contentList
    },
    // 用户角色赋值
    setRoleNo() {
      if (JSON.parse(localStorage.getItem("user")).roleNo.includes(",")) {
        this.roleNo = JSON.parse(localStorage.getItem("user"))["roleNo"].split(',')
      } else {
        this.roleNo.push(JSON.parse(localStorage.getItem("user"))["roleNo"])
      }
    },
    complexCommittee,
    selectedItem() {
      return this.items.at(this.selectedItemIndex);
    },
    //审批状态
    getState() {
      switch (this.selectedStatus) {
        case "0":
          return "待审批";
        case "1":
          return "已审批";
        case "2":
          return "有异议";
        case "3":
          return "未通过"
      }
    },
    /**
     * 获取班级
     */
    getClass() {
      request.get("/info_class/getClassNoByAccount?accountNo="+JSON.parse(localStorage.getItem("user")).accountNo).then(res => {
        this.cascaderOptions = res.data.data
      })
    },
    /**
     * 获取选中班级的数据
     */
    handleCascaderChange() {
      this.selectedStudentIndex = 0
      this.selectedItemIndex = 0
      this.finish = false
      let classNo = this.selectedOptions.at(2)
      // 获取最新年度的数据
      request.get("/complex_related/getListByClassNoAndYear?classNo=" + classNo + "&year=" + this.year + "&state=" + this.selectedStatus).then(res => {
        this.students = res.data.data;
        if (this.students.length !== 0) {
          this.items = this.students.at(this.selectedStudentIndex).contentList
        } else {
          this.items = []
        }
      })
    },
    // 驳回操作
    reject() {
      this.$prompt('请输入驳回原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        if (value === null || value === "") {
          this.$message({
            type: 'error',
            message: '请输入驳回原因'
          });
          return
        }
        this.students[this.selectedStudentIndex].rejection = value
        request.post("/complex_related/reject", this.students[this.selectedStudentIndex])
        this.$message({
          type: 'success',
          message: '驳回成功'
        });
        // 驳回后换下一个同学
        this.selectedStudentIndex++
        this.$store.commit('setStudentIndex', this.selectedStudentIndex); // 提交索引到 store
        this.selectedItemIndex = 0
        this.finish = false
      })
    },
    // 重新审批
    resetState() {
      this.$confirm('是否需要重新审批?', '提示', {
        confirmButtonText: '需要',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.get("/complex_related/resetState?id=" + this.students[this.selectedStudentIndex].id).then(res => {
          if (res.data.data) {
            this.$message({
              type: 'success',
              message: '操作成功',
            });
            this.selectedStudentIndex++;
            this.$store.commit('setStudentIndex', this.selectedStudentIndex); // 提交索引到 store
            this.selectedItemIndex = 0
            this.finish = false
          }
        })
      })
    },
    // 整体查看点击
    approve() {
      this.$store.commit('setAccountN0', this.students[this.selectedStudentIndex].accountNo)
      this.$store.commit('complexUpdateSetTrue', this.items)
      this.$store.commit("setYear", this.students.at(this.selectedStudentIndex).year)
    },
    getNextStudent() {
      request.get("/complex_related/submit?id=" + this.students[this.selectedStudentIndex].id).then(res => {
        this.selectedStudentIndex++;
        this.$store.commit('setStudentIndex', this.selectedStudentIndex); // 提交索引到 store
        this.selectedItemIndex = 0
        this.finish = false
        this.items = this.students.at(this.selectedStudentIndex).contentList
      })
    },
    // 该同学下一项综测项目
    nextItem() {
      // 下一项操作
      if (this.selectedItemIndex < this.students.at(this.selectedStudentIndex).contentList.length - 1) {
        this.selectedItemIndex++;
      }
      if (this.selectedItemIndex === this.students.at(this.selectedStudentIndex).contentList.length - 1) {
        this.finish = true;
      }
    },
    prevItem() {
      // 上一项操作
      if (this.selectedItemIndex > 0) {
        this.selectedItemIndex--;
        this.finish = false
      }
    },
    // 检查文件类型
    checkFileType(file) {
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      // jpeg,.png,.jpg,.bmp,.gif
      if (
          fileType === '.jpg' ||
          fileType === '.png' ||
          fileType === '.jpeg'
      ) {// 验证通过
      } else {
        this.$message.error(
            '不是,jpeg,.png,.jpg文件,请上传正确的图片类型'
        )
        return false
      }
    },
    // 证明材料上传成功回调
    handleSuccess(res) {
      res = aes.decrypt(res)
      this.projectObject.photoUrl = res.data
      this.$message({
        type: 'success',
        message: '上传成功!'
      });
    },
  },
};
</script>

<style scoped>
.approval-page {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  min-height: 88vh;
  justify-content: space-between;
}

.right-div {
  width: 250px;
  height: 80vh;
  position: fixed;
  top: 15vh;
  right: 0;
  background-color: #ffffff;
  padding: 10px;
  overflow-y: auto;
}
.content {
  flex: 1;
}

.selection-container {
  display: flex;
}

.flex-item {
  flex-grow: 1;
}

.bottom-buttons {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.info-line {
  display: flex;
  justify-content: center;
}

.selected-info {
  text-align: center;
}
.info-footer {
  text-align: center;
  margin-top: 20px;
}

.project-image {
  width: auto;
  max-height: 70vh;
  max-width: 100%;
  margin-top: 10px;
  object-fit: cover; /* 图片填充整个容器并保持纵横比 */
}

.student-list {
  cursor: pointer;
  display: flex;
  flex-wrap: wrap; /* 如果希望自动换行，可以使用 wrap 属性 */
}

.student {
  margin-right: 10px; /* 可以调整学生之间的间距 */
}

.form-row {
  display: flex;
  margin-bottom: 10px; /* 调整行与行之间的间距 */
}

.form-item {
  flex: 1; /* 让内部元素均分剩余空间 */
}

label {
  display: inline-block;
  width: 150px; /* 根据实际情况调整宽度 */
}
</style>
